package org.ee.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
 * 解码器
 * @Author jokr
 * @Date 2025/8/13 下午4:53
 */
public class ProtocolDecoder extends ByteToMessageDecoder {
    private static final Logger logger = LogManager.getLogger(ProtocolDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int len=byteBuf.readableBytes();
        byte[] b=new byte[len];
        byteBuf.readBytes(b);
        logger.info("MyprotocolDecoder decode {}",new String(b));
        list.add(byteToHexString(b));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("通道:[{}],TCP连接异常！，信息：{}",ctx.channel().id(),cause.getMessage());
    }

    /**
     * 字节数组转16进制
     * @param bArray
     * @return
     */
    public String byteToHexString(byte[] bArray){
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}
